package com.keepers.repair.fragment

import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.keepers.repair.R
import com.keepers.repair.adapter.TaskAdapter
import com.keepers.repair.model.TaskModel
import com.keepers.repair.utils.Api
import com.keepers.repair.utils.getUser
import org.jetbrains.anko.find

class MainTaskFragment : Fragment() {

    private lateinit var refreshLayout: SwipeRefreshLayout
    private lateinit var recyclerView: RecyclerView
    private val taskList = mutableListOf<TaskModel>()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_main_tasks, container, false)

        this.refreshLayout = view.find(R.id.task_refresh_layout)
        this.recyclerView = view.find(R.id.task_recycler_view)

        this.refreshLayout.setOnRefreshListener(this::refreshList)
        this.recyclerView.layoutManager = LinearLayoutManager(this.context)
        this.recyclerView.adapter = TaskAdapter(taskList)

        refreshList()

        return view
    }



    private fun refreshList() {
        getUser(this.context!!)?.apply {
            refreshLayout.isRefreshing = true
            Api.getTasks(this.GroupGid!!, this.Gid) { list ->
                taskList.clear()
                list.forEach { taskList.add(it) }
                recyclerView.adapter?.notifyDataSetChanged()
                refreshLayout.isRefreshing = false
            }
        }
    }
}
